import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Jiange
 * @create 2021-05-13-14:39
 */

/**
 * 读锁是共享锁 允许其他操作进入 写锁是排他锁 不允许其他任何操作进入
 */

class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key,Object value){
        readWriteLock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"\t"+"准备存");
        map.put(key, value);
        System.out.println(Thread.currentThread().getName()+"\t"+"存数据"+value);
        readWriteLock.writeLock().unlock();
    }

    public void get(String key){
        readWriteLock.readLock().lock();
        System.out.println(Thread.currentThread().getName()+"\t"+"取数据");
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"\t"+"取数据"+o);
        readWriteLock.readLock().unlock();
    }
}

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(()->{
                myCache.put(finalI+"",finalI+"");
            },String.valueOf(finalI)).start();
        }

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    TimeUnit.MILLISECONDS.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                myCache.get(finalI+"");
            },String.valueOf(finalI)).start();
        }
    }
}
